package com.example.mobileeducationstudentv;

import java.io.*;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class Display extends Activity {

	// variable declarations
	int depth;
	String folderName;
	String subFolderName;
	ImageListAdapter adapter;
	File[] list;
	ListView listView;
	FileDataStorage db;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// initialize database
		db = new FileDataStorage(this);
		// initialize display
		setContentView(R.layout.display);
		// initialize listview and buttons
		listView = (ListView) findViewById(R.id.listview);
		final Button buttonBack = (Button) findViewById(R.id.btnBack);
		final Button buttonClear = (Button) findViewById(R.id.btnClear);
		buttonBack.setText("Back");
		// depth to keep track of folder structure
		depth = 0;
		// set filename and subfoldername to empty if depth is 0
		folderName = "";
		subFolderName = "";
		// back button should go up a folder level if in a bigger depth than 0,
		// otherwise, finish activity
		buttonBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (depth < 1) {
					// goto main menu
					finish();
					depth = 0;
					folderName = "";
				} else if (depth == 2) {
					depth = 1;
					subFolderName = "";
					RefreshList();
				} else {
					// go to folder list
					depth = 0;
					folderName = "";
					subFolderName = "";
					RefreshList();
				}
			}
		});
		// clear button that clears the table that stores whether a file is read
		buttonClear.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				db.clearFiles();
				RefreshList();
			}
		});
		// populate list adapter
		try {
			RefreshList();
		}
		// if folder not found
		catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error: Study folder not found", Toast.LENGTH_LONG).show();
			finish();
		}
	}

	// function that checks for current files in designated subject folder and
	// populates the listview with files and folders found
	public void RefreshList() {

		final String sdcard = Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ "/MobileEducation/Subjects/"
				+ folderName
				+ "/" + subFolderName + "/";
		list = GetFiles(sdcard);
		Boolean[] readFiles = new Boolean[list.length];
		String[] myFiles = new String[0];
		if (list.length > 0) {
			myFiles = new String[list.length];
			for (int i = 0; i < list.length; i++) {
				myFiles[i] = list[i].getName();
				readFiles[i] = db.isFileRead(list[i].getAbsolutePath());
			}
		}
		adapter = new ImageListAdapter(this, myFiles, readFiles);

		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			// open a file with associated app if found, otherwise display toast
			// with error message
			// open a folder and increment the depth, appent
			// foldername/subfoldername to folder opened, depending on depth
			@Override
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {
				final String item = (String) parent.getItemAtPosition(position);
				File file = new File(sdcard + item);
				//logging test
				Log.e("TEST", "Is dir: " + Boolean.toString(file.isDirectory())
						+ " Depth: " + Integer.toString(depth) + " Name: "
						+ file.getName() + " Path: " + file.getAbsolutePath());
				if ((file.isDirectory()) && (depth == 0)) {
					depth = 1;
					folderName = file.getName();
					RefreshList();
				} else if ((file.isDirectory()) && (depth == 1)) {
					depth = 2;
					subFolderName = file.getName();
					RefreshList();
				} else {
					db.readFile(file.getAbsolutePath());
					openFile(Uri.parse("file://" + file.getAbsolutePath()));
					RefreshList();
				}

			}
		});
	}

	// retrieve files from designated folder
	public File[] GetFiles(String DirectoryPath) {

		File f = new File(DirectoryPath);
		f.mkdirs();
		File[] files = f.listFiles();
		return files;
	}

	// get extension type
	public static String getMimeType(String url) {
		String type = null;
		String extension = MimeTypeMap.getFileExtensionFromUrl(url);
		if (extension != null) {
			MimeTypeMap mime = MimeTypeMap.getSingleton();
			type = mime.getMimeTypeFromExtension(extension);
		}
		return type;
	}

	// open file with app associated with extension if found, otherwise display
	// toast with error message
	private void openFile(Uri uri) {
		Intent viewIntent = new Intent();
		viewIntent.setAction(Intent.ACTION_VIEW);
		viewIntent.setDataAndType(uri, getMimeType(uri.toString()));
		List<ResolveInfo> resolved = getPackageManager().queryIntentActivities(
				viewIntent, 0);
		if (resolved != null && resolved.size() > 0) {
			startActivity(viewIntent);
		} else {
			Toast.makeText(getApplicationContext(),
					"Could not open this file, Reader not installed.",
					Toast.LENGTH_LONG).show();
		}
	}
}
